package com.deep.bilibili.service;


import com.deep.bilibili.config.UploadConfig;
import com.deep.bilibili.exception.UploadException;
import com.deep.bilibili.util.UploadUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Service("UploadService")
public class UploadService {

    private final Path fileStorageLocation;

    @Autowired
    public UploadService(UploadConfig uploadConfig) {
        String uploadDir = uploadConfig.getUploadDir();
        if (StringUtils.isNotBlank(uploadDir)) {

        } else {
            uploadDir = UploadService.class.getClassLoader().getResource("uploads").getPath();
        }
        this.fileStorageLocation = Paths.get(uploadDir).toAbsolutePath().normalize();

        try {
            if (!Files.exists(this.fileStorageLocation)) {
                Files.createDirectories(this.fileStorageLocation);
            }
        } catch (Exception ex) {
            throw new UploadException("无法创建将存储上传文件的目录。", ex);
        }
    }

    public String storeFile(MultipartFile file) {
        return UploadUtil.storeFile(this.fileStorageLocation, file);
    }

    public String storeFile(MultipartFile file, String filePath) {
        return UploadUtil.storeFile(this.fileStorageLocation, filePath, file);
    }

    public String storeFile(MultipartFile file, String filePath, String filename) {
        return UploadUtil.storeFile(this.fileStorageLocation, filePath, filename, file);
    }

    public Resource loadFileAsResource(String fileName) {
        return UploadUtil.loadFileAsResource(this.fileStorageLocation, fileName);
    }

    public String getFullPath(String filePath) {
        return this.fileStorageLocation + "/" + filePath;
    }
}
